//
//  MusicEngine.swift
//  ChineseChess
//
//  Created by 左忠飞 on 2021/1/21.
//

import UIKit
import AVFoundation

class MusicEngine: NSObject {
    //音频引擎单例
    static let shareInstance = MusicEngine()
    
    //音频播放器
    var player:AVAudioPlayer?
    
    private override init() {
        //获取音频文件
        let path = Bundle.main.path(forResource: "music", ofType: "mp3")
        let data = try! Data(contentsOf: URL(fileURLWithPath: path!))
        player = try! AVAudioPlayer(data: data)
        //进行音频的懒加载
        player?.prepareToPlay()
        //设置音频循环播放次数
        player?.numberOfLoops = -1
    }
    
    //提供一个开始播放背景音频的方法
    func playBackgroundMusic() {
        //如果音频没有在播放状态,就进行播放
        if !player!.isPlaying {
            let result = player?.play()
            print("播放音乐:\(result! ? "成功" : "失败")")
        }
    }
    
    //提供一个停止播放背景音频的方法
    func stopBackgroundMusic() {
        if player!.isPlaying {
            player?.stop()
        }
    }
}
